﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using Wolfut.MirageEE.Domain.CommonUtilities;
using Wolfut.MirageEE.UI.UICommonUtilities;

namespace Wolfut.MirageEE.UI.UIBaseComponents
{
    public partial class MirageEEFormBase : FormBase
    {
        public MirageEEFormBase()
        {
            InitializeComponent();
        }

        #region "fields & property"

        //窗体状态
        public Constant.FormState formState = Constant.FormState.Unchanged;
        //保存并新增的时候check是否保存通过
        public bool noNeedSaveAndNew = false;
        //protectedfocusRow的index，add,remove,delete,edit,refresh记录的时候使用到
        protected int RowIndex = -1;
        //窗体是否已经加载，如果窗体第一次load，则跳过form_Activated事件,用在窗体刷新的时候使用
        protected bool m_formLoaded = false;

        /// <summary>
        /// 返回到主窗体是否需要刷新
        /// </summary>
        public bool needRefresh = false;

        public object CurrentRow = null;
        //print export
        protected GridExportPrintClass exportPrintHelper;
        /// <summary>
        /// 每个Form的业务名称
        /// </summary>
        protected virtual string FormBusinessName
        {
            get
            {
                return this.Text;
            }
        }

        #endregion

        #region "MessageBox  Show"

        protected void ShowTransactionInfo(string successTransactionInfo)
        {
            if (!this.DesignMode)
            {
                this.ShowTransactionInfo(successTransactionInfo);
            }
        }

        protected void ShowTransactionInfo()
        {
            if (!this.DesignMode)
            {
                CustomerShowMessage.ShowTransactionInfo();
            }
        }

        public DialogResult ShowErrorMessage(string messages)
        {
            return CustomerShowMessage.ShowErrorMessage(messages);
        }

        public DialogResult ShowInformationMessage(string messages)
        {
            return CustomerShowMessage.ShowInformationMessage(messages);
        }

        public DialogResult ShowClosingMessage(string messageId, params string[] paraList)
        {
            return CustomerShowMessage.ShowClosingMessage(messageId, paraList);
        }

        public DialogResult ShowMessage(string messageId, params string[] paraList)
        {
            return CustomerShowMessage.ShowMessage(messageId, paraList);
        }

        public DialogResult ShowCustomMessage(string messageId, string message)
        {
            return CustomerShowMessage.ShowCustomMessage(messageId, message);
        }

        public DialogResult ShowCustomMessage(string[] messageId, string[] message)
        {
            return CustomerShowMessage.ShowCustomMessage(messageId, message);
        }

        protected bool ConfirmProceed(string additionInfo)
        {
            return CustomerShowMessage.ConfirmProceed(additionInfo);
        }

        #endregion

        #region "OnLoad"

        private void MirageEEFormBase_Load(object sender, System.EventArgs e)
        {
            if (!DesignMode)
            {
                exportPrintHelper = new GridExportPrintClass(this, FormBusinessName);
                this.BindGrid(true);
            }
          
        }

        protected virtual void BindGrid(bool isDBReloadNeeded)
        {
        }

        protected virtual bool isValid()
        {
            return true;
        }

        protected override void OnLoad(System.EventArgs e)
        {
            this.KeyPreview = true;
            string fontName = Constant.FontName.Microsoft_Sans_Serif;
            float fontSize = Constant.FontSize;
            try
            {
                if (!(ConfigurationSettings.AppSettings["MirageEE.Font"] == null))
                {
                    fontName = ConfigurationSettings.AppSettings["MirageEE.Font"].ToString();
                }
                if (!(ConfigurationSettings.AppSettings["MirageEE.FontSize"] == null))
                {
                    fontSize = float.Parse(ConfigurationSettings.AppSettings["MirageEE.FontSize"].ToString());
                }
                this.Font = new Font(fontName, fontSize);
            }
            catch
            {
                this.Font = new Font(Constant.FontName.Microsoft_Sans_Serif, fontSize);
            }
            //			Color backColor = SystemColors.Control; 
            //			try 
            //			{ 
            //				if (!(ConfigurationSettings.AppSettings["MirageEE.BackColor"] == null)) 
            //				{ 
            //					try 
            //					{ 
            //						backColor = Color.FromName(ConfigurationSettings.AppSettings["MirageEE.BackColor"].ToString()); 
            //					} 
            //					catch 
            //					{ 
            //						backColor = ColorTranslator.FromOle(int.Parse(ConfigurationSettings.AppSettings["MirageEE.BackColor"].ToString(),System.Globalization. NumberStyles.HexNumber)); 
            //					} 
            //				} 
            //				this.BackColor = backColor; 
            //			} 
            //			catch 
            //			{ 
            //				this.BackColor = SystemColors.Control; 
            //			} 
            //object cloneImage;
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetAssembly(typeof (MirageEEFormBase));
            string iconName = Constant.MirageEEImages.bg_png;
            //int index;
            //string myStreamName = "Wolfut.MirageEE.UI.";
            //			string[] myArray = myAssembly.GetName().Name.Split('.'); 
            //			for (index = 0; index <= myArray.Length - 1; index++) 
            //			{ 
            //				myStreamName = myStreamName + myArray[index] + "."; 
            //			} 

            base.OnLoad(e);
            if (this.IsMdiContainer)
            {
                iconName = Constant.MirageEEImages.abacus_ico;
            }
            else
            {
                iconName = Constant.MirageEEImages.abacus_ico;
            }
            string AssemblyName = Constant.AssemblyName;
            Stream myStream = myAssembly.GetManifestResourceStream(AssemblyName + iconName);
            this.Icon = new Icon(myStream);
            m_formLoaded = true;            
        }

        protected void CloseMe()
        {
            //if (this.MdiParent != null)
            //{
            //    (this.MdiParent as MainForm).pictureEdit1_Click(null, null);

            //}
            //else
            //{
            //    this.Close();
            //}
            this.Close();
        }

        #endregion

        #region "public method for Forms"

        protected virtual void StatusBarDisplayText(TreeListNode node)
        {
        }

        protected virtual void SaveNodeToDataBase(TreeListNode node)
        {
        }

        protected void SetCheckedNode(TreeListNode node, TreeList treeList1, MirageEEFormBase form)
        {
            CheckState check = (CheckState) node.GetValue("Check");
            if (check == CheckState.Indeterminate || check == CheckState.Unchecked) check = CheckState.Checked;
            else check = CheckState.Unchecked;
            treeList1.BeginUpdate();
            node["Check"] = check;
            if (form != null)
            {
                form.StatusBarDisplayText(node);
                form.SaveNodeToDataBase(node);
            }
            SetCheckedChildNodes(node, check, form);
            SetCheckedParentNodes(node, check, form);
            treeList1.EndUpdate();
        }

        protected void SetCheckedNode(TreeListNode node, TreeList treeList1)
        {
            CheckState check = (CheckState) node.GetValue("Check");
            if (check == CheckState.Indeterminate || check == CheckState.Unchecked) check = CheckState.Checked;
            else check = CheckState.Unchecked;
            treeList1.BeginUpdate();
            node["Check"] = check;
            SetCheckedChildNodes(node, check);
            SetCheckedParentNodes(node, check);
            treeList1.EndUpdate();
        }

        protected void SetSingleCheckedNode(TreeListNode node, TreeList treeList1, CheckState check)
        {
            treeList1.BeginUpdate();
            node["Check"] = check;
            treeList1.EndUpdate();
        }

        protected void SetRecrusiveCheckedNode(TreeListNode node, TreeList treeList1, CheckState check)
        {
            treeList1.BeginUpdate();
            node["Check"] = check;
            SetCheckedChildNodes(node, check);
            SetCheckedParentNodes(node, check);
            treeList1.EndUpdate();
        }

        //protected virtual void UpdateStatusPane(MirageEEFormBase form, string statusInfo)
        //{
        //    MainForm parent = form.MdiParent as MainForm;
        //    parent.UpdateStatusPane(statusInfo);

        //}

        protected void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i]["Check"] = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        protected void SetCheckedChildNodes(TreeListNode node, CheckState check, MirageEEFormBase form)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i]["Check"] = check;
                //
                form.SaveNodeToDataBase(node.Nodes[i]);
                //
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        protected void SetCheckedParentNodes(TreeListNode node, CheckState check, MirageEEFormBase form)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    if (!check.Equals(node.ParentNode.Nodes[i]["Check"]))
                    {
                        b = !b;
                        break;
                    }
                }
                node.ParentNode["Check"] = b ? CheckState.Indeterminate : check;
                //
                form.SaveNodeToDataBase(node.ParentNode);
                //
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }

        protected void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    if (!check.Equals(node.ParentNode.Nodes[i]["Check"]))
                    {
                        b = !b;
                        break;
                    }
                }
                node.ParentNode["Check"] = b ? CheckState.Indeterminate : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }

        protected void SetCloseButtonCaption(bool isClosed, BaseButton edit)
        {
            if (isClosed)
            {
                edit.Text = Constant.Close;
            }
            else
            {
                edit.Text = Constant.Cancal;
            }
        }

        protected bool IsClosedState(BaseButton edit)
        {
            if (edit.Text.Trim() == Constant.Close)
                return true;
            return false;
        }

        protected void RegisterkeyEnterEvents(MirageEEFormBase form, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char) (int) Keys.Enter)
            {
                if (form.ActiveControl is DevExpress.XtraEditors.TextBoxMaskBox)
                {
                    DevExpress.XtraEditors.TextBoxMaskBox maskBox =
                        this.ActiveControl as DevExpress.XtraEditors.TextBoxMaskBox;
                    if (maskBox.OwnerEdit.GetType() == typeof (DevExpress.XtraEditors.MemoEdit) ||
                        maskBox.OwnerEdit.GetType() == typeof (DevExpress.XtraEditors.MemoExEdit))
                    {
                        return;
                    }
                }
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
        }

        protected virtual void HelpMe(string p)
        {
        }

        #endregion

        #region "gridView"

        protected int[] CheckGridViewSelectedCount(GridView view, bool mutiItems)
        {
            
            return GridOperations.CheckGridViewSelectedCount(view,mutiItems);
        }

        public virtual void RefreshGridView(GridView view)
        {

            GridOperations.RefreshGridView((view));
        }

        #endregion

        #region "Other events"
        private void MirageEEFormBase_KeyPress(object sender, KeyPressEventArgs e)
        {
            RegisterkeyEnterEvents(this, e);
        }

        private void MirageEEFormBase_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断数据是否dirty
            if(this.Dirty)
            {
                //showmessage
                //e.Cancel = true;
            }
        }

        protected virtual  void CloseButton_Click(object sender, EventArgs e)
        {
            this.CloseMe();
        }
        protected virtual void HelpButton_Click(object sender, EventArgs e)
        {
            this.HelpMe(this.Name);
        }
        protected virtual void ChooseButton_Click(object sender, EventArgs e)
        {

        }
        #endregion
    }
}